from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from user.myserializers import UserUnSerializer
from .utils import encrypt, jwt_token

from .models import *


# Create your views here.

# 注册
class RegisterView(APIView):
    def get(self, request):
        pass

    def post(self, request):
        # 获取用户名
        username = request.data.get('username')
        # 获取密码
        password = request.data.get('password')
        password2 = request.data.get('password2')
        # 是否完整
        if not all([username, password, password2]):
            return Response({'status': 201, 'msg': '信息不完整', 'data': ''})
        # 确认密码
        if password != password2:
            return Response({'status': 202, 'msg': '两次密码输入不一致', 'data': ''})
        user = UserModel.objects.filter(username=username).first()
        # 判断用户是否存在
        if user:
            return Response({'status': 203, 'msg': '用户已存在', 'data': ''})
        # 存入数据库
        data = {'username': username, 'password': password}
        obj = UserUnSerializer(data=data)
        if obj.is_valid():
            obj.save()
        return Response({'status': 200, 'msg': '注册成功', 'data': ''})


# 登录
class LoginView(APIView):
    def get(self, request):
        pass

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = UserModel.objects.filter(username=username, password=password).first()
        if user:
            return Response({'status': 200, 'msg': '登录成功', 'token': jwt_token(user)})
        return Response({'status': 202, 'msg': '用户名或密码不正确', 'data': ''})
